//
//  ShellLanguageManager.m
//  ShellWallert
//
//  Created by lvzhao on 2019/5/14.
//  Copyright © 2019 吕VV. All rights reserved.
//

#import "ShellLanguageManager.h"

@interface ShellLanguageManager()

@property (nonatomic,strong) NSBundle *bundle;

@end

@implementation ShellLanguageManager

+ (instancetype)shareInstance{
    static ShellLanguageManager * languageManger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        languageManger = [[ShellLanguageManager alloc]init];
    });
    return languageManger;
}

//初始化语言
- (void)initUserLanguage{
    
    //获取当前语言
    __block  NSString *currentLanguage = [self currentLanguage];
    if(currentLanguage.length == 0){
        NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
        NSData *data = [NSData dataWithContentsOfURL:ipURL];
        if(!data){
            [self setUserlanguage:@"English"];
            return;
        }
        NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *ipStr = nil;
        if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
            ipStr = ipDic[@"data"][@"ip"];
        }
        @weakify(self);
        NSString *url = [NSString stringWithFormat:@"http://apis.juhe.cn/ip/ipNew?ip=%@&key=e2a0ddd8aa7463579a1d18da808868dc",ipStr];
        [LZNetworkingManager lz_request:@"get" url:url params:nil success:^(id  _Nullable responseObject) {
          if([responseObject[@"resultcode"] isEqualToString:@"200"]){
              @strongify(self);
              NSDictionary *resultDictionary = responseObject[@"result"];
              NSString *country = resultDictionary[@"Country"];
              NSString *language = @"";
              if([country isEqualToString:@"中国"]){
                  language = @"繁体中文";
              }  else if([country isEqualToString:@"日本"]){
                  language = @"日語";
              } else if([country isEqualToString:@"韩国"]){
                  language = @"한국어";
              } else {
                  language = @"English";
              }
            
              [self setUserlanguage:language];
          }
        } failure:^(NSError * _Nullable error) {
          
        }];
        //保存当前语言
        [self saveLanguage:@"en"];
        
    }
    //改变配置文件的内容
    [self changeBundle:[self currentLanguage]];
}

//设置语言
- (void)setUserlanguage:(NSString *)language {
    
    if ([language isEqualToString:@"English"]){
        language = @"en";
    } else if ([language isEqualToString:@"繁体中文"]){
        language= @"zh-HK";
    } else if ([language isEqualToString:@"한국어"]){
        language= @"ko";
    } else if ([language isEqualToString:@"日語"]){
        language= @"ja";
    }
    
    
    if (![[self currentLanguage] isEqualToString:language]) {
        
        [LZToolCache setObject:language forKey:k_locationLanguge];
        
        [self changeBundle:language];
        //改变完成之后发送通知，告诉其他页面修改完成，提示刷新界面
        [[NSNotificationCenter defaultCenter] postNotificationName:k_APPLanguageWillChangeNotificationName object:nil];
    }
}



#pragma mark - tool
//获取配置文件
- (void)changeBundle:(NSString *)language{
    NSString * path = [[NSBundle mainBundle] pathForResource:[self languageFormat:language] ofType:@"lproj"];
    self.bundle = [NSBundle bundleWithPath:path];
}

//获取语言
- (NSString *)currentLanguage {
    
    NSString *currentLanguage = LZToolCache.locationLanguge;
    return currentLanguage;
}


- (NSString *)language{
    
    
    NSString *currentLanguage = [self currentLanguage];
    
    if([currentLanguage  isEqualToString:@"zh-HK"]){
        return @"繁体中文";
    } else if([currentLanguage containsString:@"ja"]){
        return @"日語";
    } else if([currentLanguage containsString:@"ko"]){
        return @"한국어";
    } else {
        return @"English";
    }
}

//保存语言
- (void)saveLanguage:(NSString *)language {
    /*
     繁体 zh-Hant-HK
     英文 en-HK
     中文 zh-Hans-HK
     */
    [LZToolCache setObject:language forKey:k_locationLanguge];
}


//语言和语言对应的.lproj的文件夹前缀不一致时在这里做处理
- (NSString *)languageFormat:(NSString*)language {

    return language;
}

//获取当前语种下的内容
- (NSString *)localizedStringForKey:(NSString *)key {
    
    return [self localizedStringForKey:key tableName:@"Localizable"];
}

//查询语言的文字 字典的样式
- (NSString *)localizedStringForKey:(NSString *)key tableName:(NSString *)tableName{
    if (!self.bundle) {
        [self initUserLanguage];
    }
    if (!tableName) {
        tableName = @"Localizable";
    }
    
    if (key.length > 0) {
        if (self.bundle) {
            NSString *str = NSLocalizedStringFromTableInBundle(key, tableName, self.bundle, nil);
            if (str.length > 0) {
                return str;
            }
        }
    }
    return key;
}
@end
